package com.ogawa.project6602.viewmodel

import androidx.lifecycle.MutableLiveData
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.projectcommon.utils.dataConvert
import com.ogawa.projectcommon.utils.launch
import com.ogawa.projectcommon.bean.DiyBean
import com.ogawa.projectcommon.constants.Constant
import com.ogawa.projectcommon.dboperation.OperationDB
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.projectcommon.service.DiyApiService
import com.ogawa.projectcommon.utils.ProjectSpUtils

class DiyViewModel : BaseViewModel() {
    private val diyService = RetrofitManager.INSTANCE.createService(DiyApiService::class.java)
    private val diyDao = OperationDB().db.getDiyProgramDao()
    private val userInfo = ProjectSpUtils.getUserInfo()
    val diyPrograms = MutableLiveData<List<DiyBean>>()
    val diyBeanData = MutableLiveData<DiyBean>()

    fun getDiyProgram() {
        launch({
            loadState.value = LoadState.Loading("")
            if (userInfo.isVisitor) {
                diyPrograms.value = diyDao.getDiyBeans()
            } else {
                diyPrograms.value =
                    diyService.getDiyProgram(ProjectSpUtils.getCurDeviceTypeCode(), userInfo.user.id)
                        .dataConvert()
            }
            loadState.value = LoadState.Success("")
        }, { loadState.value = LoadState.Fail(it.message!!) })
    }

    fun saveDiyProgram(diyBean: DiyBean) {
        launch({
            loadState.value = LoadState.Loading("")
            if (userInfo.isVisitor) {
                var getBean = diyDao.queryDiyByIndexAndCode(
                    diyBean.appIndex!!.toInt(),
                    ProjectSpUtils.getCurDeviceTypeCode()
                )
                if (getBean == null) {//插入
                    getBean = DiyBean(
                        ProjectSpUtils.getCurDeviceTypeCode(),
                        diyBean.diyName,
                        diyBean.content,
                        diyBean.appIndex
                    )
                    diyDao.insertItem(getBean)
                } else {//更新
                    getBean.diyName = diyBean.diyName
                    getBean.content = diyBean.content
                    diyDao.updateDiyInfo(getBean)
                }
                diyBeanData.value = getBean
            } else {
                diyBean.userId = userInfo.user.id
                diyBeanData.value = diyService.saveDiyProgram(diyBean).dataConvert()
            }
            loadState.value = LoadState.Success("")
        }, { loadState.value = LoadState.Fail(it.message!!) })
    }

    fun shareDiy(id: String) {
        launch({
            loadState.value = LoadState.Loading("")
            diyService.shareDiy(id).dataConvert()
            loadState.value = LoadState.Success("1")
        }, { loadState.value = LoadState.Fail(it.message!!) })
    }
}